<?php
    defined('M2_MICRO') or die('Direct Access to this location is not allowed.');

    /**
      * @desc Controller class
      * @package Niiar Drop Box
      * @author Alexander Chaika
      */
    class Controller extends Error {
        var $name = '';

        /**
          * Class constructor
          */
        public function  __construct() {
            $this->view = $this->getView();
            $this->model = $this->getModel();
        }
        
        /**
          * Dispatch action
          * @return mixed $result
          */
        public function dispatch() {
            global $system, $error, $config;

            // we have startup errors
            if ($error->isPresent()) {
                $this->view->offline();
                return;
            }

            // load module
            $module = $this->loadModule($system->getCmd('module', 'front'));
            $result = $module->dispatch(
                $system->getCmd('action', ''),
                $system->getCmd('task', '')
            );

            // render page
            $this->view->render($result);
            return;
        }

        /**
          * If we have startup errors
          */
        public function offline() {
            $this->view->offline($result);
        }
        
        private function loadModule($module, $default = 'front') {
            global $config, $error;
            
            // check modules existance
            if (file_exists($config['doc_root'].'/includes/'.$module.'/controller.php')) {
                require_once $config['doc_root'].'/includes/'.$module.'/controller.php';
                $module_name = ucfirst($module).'Controller';
            } else {
                require_once $config['doc_root'].'/includes/'.$default.'/controller.php';
                $module_name = ucfirst($default).'Controller';
            }
            
            return new $module_name();
        }

        protected function getModel() {
            require_once 'model.php';
            $model_name = $this->name.'Model';
            return new $model_name();
        }

        protected function getView() {
            require_once 'view.php';
            $view_name = $this->name.'View';
            return new $view_name();
        }
    }

    // global object
    $GLOBALS['controller'] = new Controller();
?>
